package com.mediacloud.app.newsmodule.view;

import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;

import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.TextView;

import com.eventTrack.TXReportManager;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.assembly.util.AssetsManager;
import com.mediacloud.app.assembly.util.FileUtil;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.view.WebBrowser;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.component.IExposure;
import com.mediacloud.app.newsmodule.fragment.imagetext.ImageTextDetailFragment2;
import com.mediacloud.app.newsmodule.fragment.imagetext.RelatedType;
import com.mediacloud.app.reslib.util.DataInvokeUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by 陈凯 on 2017/9/21.
 */

public class PartVideoIntroduction extends BaseRelatedView implements IExposure {

    /*HListView mHListView;

      RelatedAdapter mRelatedAdapter;*/
    TextView mIntroduce;
    WebBrowser mNewsContentView;
    TextView authorName;
    TextView sourceName;



    public PartVideoIntroduction(Context context) {
        super(context);
        initView();
    }

    public PartVideoIntroduction(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public PartVideoIntroduction(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PartVideoIntroduction(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void initView() {
        super.initView();
        mIntroduce = mView.findViewById(R.id.video_sums);
        mNewsContentView = mView.findViewById(R.id.mNewsContentView);
        authorName = mView.findViewById(R.id.authorName);
        sourceName = mView.findViewById(R.id.sourceName);
        mNewsContentView.getSettings().setLoadWithOverviewMode(true);
        mNewsContentView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        header.setMoreListener(v -> {
            if (v.getId() == R.id.moreText) {
                if (componentItem != null) {
                    //集中处理更多点击事件
                    TXReportManager.getInstance().subtab_more_clk(componentItem.title);
                }
            }
        });
    }
    @Override
    public void setExpandStyle() {
        //header.hideTitleView();
//        header.getTitleMoreTv().setVisibility(View.GONE);
//        header.getTitleNameText().setVisibility(View.GONE);
//        header.getTitleLine().setVisibility(View.GONE);
        header.getRootTitle().setVisibility(View.GONE);
    }


    @Override
    public void setBuildData() {
        super.setBuildData();

        if (articleItem != null) {
            if (!TextUtils.isEmpty(articleItem.Author)) {
                authorName.setText(String.format("责编：%s", articleItem.Author));
                authorName.setVisibility(View.VISIBLE);
            } else {
                authorName.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(articleItem.getReferName()) && !"null".equals(articleItem.getReferName())) {
                sourceName.setText(String.format("来源：%s", articleItem.getReferName()));
                sourceName.setVisibility(View.GONE);
            } else {
                sourceName.setVisibility(View.GONE);
            }
            if (componentItem.getWidget() == RelatedType.VIDEO_RICH_SUMMARY) {

                String result = articleItem.getContent();
                if (/*TextUtils.isEmpty(result)*/false) {
                    setVisibility(View.GONE);
                } else {
                    setVisibility(View.VISIBLE);
                    mNewsContentView.setVisibility(View.VISIBLE);
                    if ("1".equals(mContext.getResources().getString(R.string.use_custom_font))) {
                        int fontResId = Utility.getResId(mContext, "font", Utility.RAW);
                        if (fontResId > 0) {
                            try {
                                String fontDes = FileUtil.CACHE + mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName + "font.ttf";
                                if (!FileUtil.isFileEnable(fontDes)) {
                                    boolean success = AssetsManager.copyRawFile2SDCard(mContext, fontResId, fontDes);
                                    //Log.w("APPTAG", "copy font " + success);
                                }
                                result = result.replaceAll(ImageTextDetailFragment2.APPFACTORY_CLIENT_LOCAL_FONT_SRC, ImageTextDetailFragment2.NATIVE_STORAGE_PREFIX + fontDes);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                    mIntroduce.setVisibility(View.GONE);

                    setContentData();
//                    mNewsContentView.loadDataWithBaseURL(null, result, "text/html; charset=utf-8", "utf-8", null);
                }
            } else {
                if (TextUtils.isEmpty(articleItem.getSummary())) {
                    setVisibility(View.GONE);

                } else {
                    setVisibility(View.VISIBLE);
                    mIntroduce.setText(articleItem.getSummary() + "");
                }
            }

        }
    }

    protected void setContentData() {
        Map<String, String> params = new HashMap<>();
        params.put("article_id", String.valueOf(articleItem.getId()));
        if (!TextUtils.isEmpty(articleItem.getPreview())) {
            params.put("preview", articleItem.getPreview());
        }
        DataInvokeUtil.ziMeiTiApi.getArticleContent(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (jsonObject.optBoolean("state")) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            String content = data.optString("content");
                            if (TextUtils.isEmpty(content)) {
//                                setVisibility(View.GONE);
                                mView.setVisibility(View.GONE);
                                mNewsContentView.setVisibility(View.GONE);
                                //authorName.setVisibility(View.GONE);
                               // sourceName.setVisibility(View.GONE);
                            } else {
                                mNewsContentView.loadDataWithBaseURL(null, content, "text/html; charset=utf-8", "utf-8", null);
                                mNewsContentView.setVisibility(View.VISIBLE);
                               // authorName.setVisibility(View.VISIBLE);
                               // sourceName.setVisibility(View.VISIBLE);
//                                setVisibility(View.VISIBLE);
                            }
//                            if (articleItem!=null&&!TextUtils.isEmpty(articleItem.Author)&&!"null".equals(articleItem.Author)) {
//                                authorName.setText(String.format("责编：%s", articleItem.Author));
//                                authorName.setVisibility(View.VISIBLE);
//                            } else {
//                                authorName.setVisibility(View.GONE);
//                            }
//                            if (articleItem!=null&&!TextUtils.isEmpty(articleItem.getReferName()) && !"null".equals(articleItem.getReferName())) {
//                                sourceName.setText(String.format("来源：%s", articleItem.getReferName()));
//                                sourceName.setVisibility(View.VISIBLE);
//                            } else {
//                                sourceName.setVisibility(View.GONE);
//                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    int getViewLayOutId() {
        return R.layout.part_video_introduce;
    }

    @Override
    void onNetDataSuccess(ArticleListData data) {

    }

    @Override
    void onNetDataFailure(Object data) {

    }


    @Override
    public List<ArticleItem> getExposureArticles() {
        if (listArticles == null) {
            listArticles = new ArrayList<>();
        }
        return listArticles;
    }

    @Override
    public ComponentItem getExposureComponentItem() {
        return null;
    }
}